package com.realm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

@Slf4j
public class MyRealm extends AuthorizingRealm {

    //授权:获取到登录成功之后的用户信息 根据用户信息去数据库中查询到对应的角色、权限
    //设置到shiro中去即可
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();
        log.info("userName:{}",userName);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //拥有admin、manage角色
        //拥有add、update权限
        authorizationInfo.addRole("admin");
        authorizationInfo.addRole("manage");

        authorizationInfo.addStringPermission("add");
        authorizationInfo.addStringPermission("update");


        return authorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //拿到用户输入的账号密码
        String userName = (String) token.getPrincipal();

        String password = new String((char[]) token.getCredentials());

        return new SimpleAuthenticationInfo(userName,password,getName());
    }
}
